import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login/flutter_login.dart';
import 'package:flutter_xxyk/constant/api.dart';
import 'package:flutter_xxyk/constant/routes.dart';
import 'package:get_it/get_it.dart';
import 'package:sp_util/sp_util.dart';

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final Dio dio = GetIt.I<Dio>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FlutterLogin(
        userType: LoginUserType.phone,
        messages: LoginMessages(userHint: 'Phone'),
        onLogin: _authUser,
        onRecoverPassword: (val) {},
        userValidator: (val) {},
      ),
    );
  }

  Future<String?> _authUser(LoginData loginData) async {
    var formData = FormData.fromMap({
      'shop_id': ApiConstant.SHOP_ID,
      'username': loginData.name,
      'password': loginData.password,
    });
    final rs = await dio.post("/h5/auth/login_by_pwd", data: formData);
    Map data = rs.data;
    SpUtil.putString("token", data['access_token']);
    SpUtil.putBool("isLogin", true);
    Navigator.of(context).pushReplacementNamed(AppRoutes.HOME);
    return null;
  }
}
